package cn.zwy.asm;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
	private String name; // 类加载器的名字

	private String path = "d:\\"; // 加载类的路径

	private final String fileType = ".class"; // class文件的扩展名

	public MyClassLoader(String name) {
		super(); // 让系统类加载器成为该类加载器的父加载器
		this.name = name;
	}

	public MyClassLoader(ClassLoader parent, String name) {
		super(parent); // 显式指定该类加载器的父加载器
		this.name = name;
	}

	@Override
	public String toString() {
		return this.name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public Class<?> findClass(String name) throws ClassNotFoundException {
		byte[] data = this.loadClassData(name);
		//完善部分by zhaoweiyong 2017-10-08 16:40:24
		if(data == null){
			return null;
		}
		//完善部分by zhaoweiyong 2017-10-08 16:40:24
		return this.defineClass(name, data, 0, data.length);
	}
	
	public Class<?> loadClassByte(String name, byte[] data){
	    return this.defineClass(name, data, 0, data.length);
	}

	public byte[] loadClassData(String name) {
		InputStream is = null;
		byte[] data = null;
		ByteArrayOutputStream baos = null;
		try {
			this.name = this.name.replace(".", "\\");
			//完善部分by zhaoweiyong 2017-10-08 16:40:24
			File file = new File(path + name + fileType);
			if(!file.exists()){
				return null;
			}
			//完善部分by zhaoweiyong 2017-10-08 16:40:24
			is = new FileInputStream(new File(path + name + fileType));
			baos = new ByteArrayOutputStream();
			int ch = 0;
			while (-1 != (ch = is.read())) {
				baos.write(ch);
			}
			data = baos.toByteArray();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			//完善部分by zhaoweiyong 2017-10-08 16:40:24
			if(data != null){
				try {
					is.close();
					baos.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			//完善部分by zhaoweiyong 2017-10-08 16:40:24
		}
		return data;
	}

	public static void main(String[] args) throws Exception {
		try {
			MyClassLoader loader1 = new MyClassLoader("loader1");
			loader1.setPath("d:\\myapp\\serverlib\\");
			MyClassLoader loader2 = new MyClassLoader(loader1, "loader2");
			loader2.setPath("d:\\myapp\\clientlib\\");
			MyClassLoader loader3 = new MyClassLoader(null, "loader3");
			loader3.setPath("d:\\myapp\\otherlib\\");
			test(loader2);
			//由loader3自己加载
			test(loader3);
		} catch (Exception e) {
		}
	}

	public static void test(ClassLoader loader) throws Exception {
		Class clazz = loader.loadClass("Sample");
		Object object = clazz.newInstance();
	}

}
